const fs = require('fs')
const Spinnies = require('spinnies')

const spinnies = new Spinnies()

const inputFileDir = 'src/static/svg'
// 生成的文件不加入版本管理
const outputFileDir = 'src/static/svg-build'
readdir(inputFileDir)

// 读取指定目录下的所有文件

function readdir(path) {
  fs.readdir(path, async function (err, files) {
    if (err) {
      console.log('Error', err)
      return
    }
    deleteFolder(outputFileDir)
    fs.mkdirSync(outputFileDir, { recursive: true })
    spinnies.add('file', { text: 'svg build...' })
    const results = files.map(async (file) => {
      const content = await readfile(`${path}/${file}`)
      const result = await writefile(`${outputFileDir}/${file}`, content.data, file)
      return result
    })
    // 所有都写入完成输出打印信息
    Promise.all(results)
      .then((res) => {
        const str = `export default [${res}]`
        fs.writeFile(`${outputFileDir}/index.ts`, str, function (error) {
          if (error) {
            console.log('Error', error)
          }
        })
        spinnies.succeed('file', { text: `✨ svg create success in ${outputFileDir}` })
      })
      .catch((errs) => {
        spinnies.fail('file', { text: errs })
      })
  })
}
// 写入文件
function writefile(path, data, file) {
  return new Promise((resolve, reject) => {
    fs.writeFile(path, data, function (errs) {
      if (errs) reject(errs)
      resolve(`"${file}"`)
    })
  })
}
// 读取单个文件
function readfile(path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, 'utf8', (err, data) => {
      //正则替换全局fill="***" 除了fill="white"
      data = data.replace(
        /<(?!rect)([^>]*)fill="([^"#][^"]*|#[^f][^"]*|#[^0-9a-fA-F][^"]*|[^"]*white[^"]*)"/gi,
        function (match, p1, p2) {
          if (p2 !== '#ffffff' && p2.toLowerCase() !== 'white') {
            return '<' + p1 + ''
          } else {
            return match
          }
        },
      )
      if (err) reject(err)
      resolve({ path, data })
    })
  })
}
// 递归删除文件
function deleteFolder(filePath) {
  if (fs.existsSync(filePath)) {
    const files = fs.readdirSync(filePath)
    files.forEach((file) => {
      const nextFilePath = `${filePath}/${file}`
      const states = fs.statSync(nextFilePath)
      states.isDirectory() ? deleteFolder(nextFilePath) : fs.unlinkSync(nextFilePath)
    })
    fs.rmdirSync(filePath)
  }
}
